package com.usian.jyzx.product.service.impl;

import com.usian.jyzx.model.entity.product.Category;
import com.usian.jyzx.product.mapper.CategoryMapper;
import com.usian.jyzx.product.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2024 07 04 14 08
 **/
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public List<Category> findCategoryByParentId(Long parentId) {
        return categoryMapper.findCategoryByParentId(parentId);
    }

    @Override
    public List<Category> findThreeCategory(Long parentId) {
        return findCategoryTree2();
    }

    /**
     * 方案一：查询多次SQL  优点：层次清晰 缺点：N次IO效率低
     *
     * @return
     */
    public List<Category> findCategoryTree1() {
        //1.先查询出所有的一级分类的集合
        List<Category> oneLevel = categoryMapper.findCategoryByParentId(0L);
        //2.遍历一级分类的集合，得到每一个一级分类
        for (Category category1 : oneLevel) {
            //3.查询出每个一级分类下的二级分类集合
            List<Category> children = categoryMapper.findCategoryByParentId(Long.valueOf(category1.getId()));
            category1.setChildren(children);
            //4.遍历每个一级分类下的二级分类集合
            for (Category category2 : children) {
                //5.查询出每个二级下的三级分类集合
                List<Category> children2 = categoryMapper.findCategoryByParentId(Long.valueOf(category2.getId()));
                category2.setChildren(children2);
            }
        }
        return oneLevel;
    }


    public List<Category> findCategoryTree2() {
        //1.查出所有分类
        List<Category> categoryList = categoryMapper.findAllCategory();
//2.得出一级分类
        List<Category> oneLevelList = categoryList.stream().filter(category -> category.getParentId().longValue() == 0).collect(Collectors.toList());
//3.遍历一级分类集合
        oneLevelList.forEach(category1 -> {
            List<Category> twoLevelList = categoryList.stream().filter(category -> category.getParentId().longValue() == category1.getId().longValue()).collect(Collectors.toList());
//得到每个一级分类下的二级分类集合
            category1.setChildren(twoLevelList);
//4.遍历二级分类集合
            twoLevelList.forEach(category2 -> {
                List<Category> threeLevelList = categoryList.stream().filter(category -> category.getParentId().longValue() == category2.getId().longValue()).collect(Collectors.toList());
//得到每个二级分类下的三级分类集合
                category2.setChildren(threeLevelList);
            });
        });
        return oneLevelList;


    }


}
